﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Services;
using GameView.Services.Comment;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Windows;

namespace GameView.ViewModels
{
    public partial class LoginViewModel : ObservableValidator
    {
        private readonly AuthService _authService;
        private readonly MenuService _menuService;
        private readonly string userName = "UIontt";
        private readonly string UserInfo = "UIo";

        public LoginViewModel(AuthService authService, MenuService menuService)
        {
            _menuService = menuService;
            _authService = authService;
            Username = SecureStorage.Load(userName);
            Password = SecureStorage.Load(Username);

            //var json = SecureStorage.Load(userName);
            //if (!json.IsNullOrEmpty())
            //    BaseSuggestions = JSON.Deserialize<List<string>>(json);
            //if (!BaseSuggestions.IsNullOrEmpty())
            //{
            //    AutoSuggestText = BaseSuggestions[0];
            //    Password = SecureStorage.Load(BaseSuggestions[0]);
            //    Suggestions = new ObservableCollection<string>(BaseSuggestions);
            //}
        }

        private List<string> BaseSuggestions { get; } = [];

        [ObservableProperty]
        private ObservableCollection<string> _suggestions = [];

        [ObservableProperty]
        private string? _autoSuggestText;

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        [Required(ErrorMessage = "用户名长度不能少于2")]
        [NotifyCanExecuteChangedFor(nameof(LoginCommand))]
        private string _username = "";

        [ObservableProperty]
        [Required(ErrorMessage = "密码长度不能少于6位")]
        [NotifyCanExecuteChangedFor(nameof(LoginCommand))]
        private string _password = "";

        [ObservableProperty]
        private bool _rememberMe = true;

         partial void OnUsernameChanged(string value)
        {
            if (value.IsNullOrEmpty())
                Password = string.Empty;
        }

#nullable enable

         partial void OnAutoSuggestTextChanged(string? oldValue, string? newValue)
        {
            Password = string.Empty;
            if (!string.IsNullOrWhiteSpace(newValue))
            {
                Username = newValue.Trim();
                var json = SecureStorage.Load(Username);
                if (!json.IsNullOrEmpty())
                    Password = json;
                if (BaseSuggestions.IsNullOrEmpty())
                    return;
                var searchResult = BaseSuggestions.Where(x => IsMatch(x, newValue));
                Suggestions = new(searchResult);
            }
            else
            {
                Suggestions = new(BaseSuggestions);
            }
        }

        [RelayCommand(CanExecute = nameof(CanLogin))]
        private async Task Login()
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                var response = await _authService.LoginAsync(Username, Password);
                if (response.StatusCode == 200)
                {
                    if (response.Data.PersonInfo == null || (response.Data.PersonInfo.RoleId != 1 && response.Data.PersonInfo.RoleId != 2))
                    {
                        GlobalMessage.Instance.ShowError("您的权限缺失！");
                        return;
                    }
                    if (RememberMe)
                    {
                        SecureStorage.Save(userName, Username);
                        SecureStorage.Save(Username, Password);
                    }
                    else
                    {
                        SecureStorage.Delete(userName);
                        SecureStorage.Delete(Username);
                    }
                    StaticValues.LoginInfo = response.Data;
                    var menums = await _menuService.GetAllAsync();
                    if (menums.Data.IsNullOrEmpty() || response.Data.Menus.IsNullOrEmpty())
                    {
                        GlobalMessage.Instance.ShowError("您的权限缺失！");
                        return;
                    }
                    StaticValues.MenuAll = menums.Data.FindAll(q => response.Data.Menus.Contains(q.Id));
                    var mw = ExtentHelper.GetService<MainWindow>();
                    mw.Show();
                    Application.Current.MainWindow?.Close();
                }
                else
                {
                    GlobalMessage.Instance.ShowError("登录失败！");
                }
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"登录失败！\n{ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        private bool CanLogin() => !string.IsNullOrWhiteSpace(Username) &&
                                 !string.IsNullOrWhiteSpace(Password);

        private static bool IsMatch(string item, string currentText)
        {
            return item.Contains(currentText, StringComparison.OrdinalIgnoreCase);
        }
    }
}